package cn.cht.controller;


import cn.cht.constant.ConmmonConstant;
import cn.cht.pojo.Order;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Objects;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/api/order")
public class OrderController {

    @Resource
    private RedisTemplate redisTemplate;
    @Resource
    private RocketMQTemplate rocketMQTemplate;

    /**
     * 用户抢购
     */
    @GetMapping("/{orderId}/{num}")
    public String getOrder(@PathVariable String orderId, @PathVariable Integer num) {
        log.info("用户抢购商品:{},数量为:{}", orderId, num);
        return checkStock(orderId, num);
    }

    /**
     * 用户支付
     */
    @GetMapping("/pay")
    public String pay(Boolean b) {
        log.info("用户支付订单状态:{}", b);
        if (Objects.isNull(b)) {
            ConmmonConstant.flag = b;
        }
        return "操作成功!";
    }

    /**
     * 检查库存逻辑
     *
     * @param num
     * @return
     */
    private synchronized String checkStock(String orderId, Integer num) {
        Integer size = (Integer) redisTemplate.opsForValue().get(ConmmonConstant.ORDKER_KEY);
        log.info("秒杀商品数量为:{}", size);
        if (size < num) {
            return "库存不足!";
        }
        redisTemplate.opsForValue().increment(ConmmonConstant.ORDKER_KEY, -1 * num);

        HashMap<String, Object> map = new HashMap<>();
        String userId = UUID.randomUUID().toString().replaceAll("-", "");
        map.put("userId", userId);
        map.put("orderId", orderId);
        map.put("num", num);
        log.info("生成数量为:{}订单!",num);
        rocketMQTemplate.syncSend(ConmmonConstant.COMMODITY_MQ,
                MessageBuilder.withPayload(JSONUtil.toJsonStr(map)).build(),
                2000, 2);
        return "用户:" + userId + "订单生成成功,请在立即支付!";
    }
}
